package controllers

import (
	"baokaobang/conf"
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"baokaobang/wechat"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/sessions"
	"os"
	"strings"
)

type Trends struct {
	Ctx iris.Context
}

// 发说说
func (c *Trends) PostCreate() interface{} {
	channel := c.Ctx.PostValue("channel")
	content := strings.TrimSpace(c.Ctx.PostValueDefault("content", ""))
	pictures := c.Ctx.PostValues("pictures")
	coverPicture := strings.TrimSpace(c.Ctx.PostValueDefault("coverPicture", ""))
	videoUrl := strings.TrimSpace(c.Ctx.PostValueDefault("videoUrl", ""))
	mType := 0

	if len(channel) <= 0 {
		return utils.CommonRes(1000, "请提供渠道", "")
	}
	if len(content) <= 0 {
		return utils.CommonRes(1000, "请输入要发表的内容", "")
	}
	if len(videoUrl) <= 0 {
		mType = 1
		if len(pictures) <= 0 {
			return utils.CommonRes(1000, "请至少上传1张图片", "")
		}
	} else {
		mType = 2
	}

	msgSec := wechat.NewMsgSec(content)
	msgSecRes, err := msgSec.Check()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("请求异常：%s", err.Error()), "")
	}
	if !msgSecRes {
		return utils.CommonRes(1000, "请不要发表敏感内容", "")
	}

	var userId int64
	if strings.EqualFold(channel, "wechat") {
		token := c.Ctx.GetHeader("token")
		claims, err := utils.ParseToken(token)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("解析token出错：%s", err.Error()), "")
		}
		userId = utils.Atoi64(claims.Id)
	} else {
		session := sessions.Get(c.Ctx)
		userId, _ = session.GetInt64(fmt.Sprintf("%sUserId", channel))
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	trends := new(models.Trends)
	trends.UserId = userId
	trends.MType = mType
	trends.Content = content
	trends.PictureList = strings.Join(pictures, ",")
	trends.CoverPicture = coverPicture
	trends.VideoUrl = videoUrl
	_, err = db.InsertOne(trends)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("说说发表失败：%s", err.Error()), "")
	}

	return utils.CommonRes(20000, "发表成功", "")
}

// 说说列表
func (c *Trends) PostList() interface{} {
	channel := c.Ctx.PostValue("channel")
	isSelf := utils.Atoi(c.Ctx.PostValueDefault("isSelf", "0"))
	curPage := utils.Atoi(c.Ctx.PostValueDefault("curPage", "1"))

	if len(channel) <= 0 {
		return utils.CommonRes(1000, "请提供渠道", "")
	}

	var userId int64

	if isSelf > 0 {
		if isSelf == 1 { // 看自己的动态
			if strings.EqualFold(channel, "wechat") {
				token := c.Ctx.GetHeader("token")
				claims, err := utils.ParseToken(token)
				if err != nil {
					return utils.CommonRes(1000, fmt.Sprintf("解析token出错：%s", err.Error()), "")
				}
				userId = utils.Atoi64(claims.Id)
			} else {
				session := sessions.Get(c.Ctx)
				userId, _ = session.GetInt64(fmt.Sprintf("%sUserId", channel))
			}
		} else if isSelf == 2 { // 看别人的动态
			userId = utils.Atoi64(c.Ctx.PostValueDefault("uid", "0"))
			if userId <= 0 {
				return utils.CommonRes(1000, "请提供用户id", "")
			}
		}
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库：%s", err.Error()), "")
	}

	start := (curPage - 1) * conf.ListDataConfig.PerPage
	trendsList := make([]models.TrendsObj, 0)
	sess := db.Table(new(models.Trends)).Alias("t").
		Join("LEFT", []string{"user", "u"}, "t.user_id = u.id").
		Join("LEFT", []string{"college", "c"}, "u.college_id = c.id").
		Limit(conf.ListDataConfig.PerPage, start).Desc("t.id")
	if isSelf > 0 {
		sess = sess.Where("t.user_id = ?", userId)
	}
	err = sess.Find(&trendsList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取动态列表：%s", err.Error()), "")
	}

	for i, trends := range trendsList {
		commentList := make([]models.CommentObj, 0)
		err = db.Table(new(models.Comment)).Alias("c").
			Join("LEFT", []string{"user", "fu"}, "c.user_id = fu.id").
			Join("LEFT", []string{"user", "tu"}, "c.to_id = tu.id").
			Where("c.trends_id = ?", trends.Trends.Id).Find(&commentList)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("无法获取动态评论列表：%s", err.Error()), "")
		}
		thumbsUpList := make([]models.ThumbsUpObj, 0)
		err = db.Table(new(models.ThumbsUp)).Alias("tu").
			Join("INNER", []string{"user", "u"}, "tu.user_id = u.id").
			Where("tu.trends_id = ?", trends.Trends.Id).Find(&thumbsUpList)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("无法获取动态点赞列表：%s", err.Error()), "")
		}
		if len(commentList) > 0 {
			trendsList[i].Trends.IsShowComment = true
		}
		if len(thumbsUpList) > 0 {
			trendsList[i].Trends.IsShowThumbsUp = true
		}
		if trendsList[i].Trends.IsShowComment || trendsList[i].Trends.IsShowThumbsUp {
			trendsList[i].IsShowThumbsUpComment = true
		}
		if trendsList[i].Trends.IsShowComment && trendsList[i].Trends.IsShowThumbsUp {
			trendsList[i].IsShowLine = true
		}
		trendsList[i].Trends.CommentList = commentList
		trendsList[i].Trends.ThumbsUpList = thumbsUpList
		trendsList[i].Trends.CreatedShow = trends.Trends.Created.Format("01-02 15:04")
		pictures := strings.Split(trends.Trends.PictureList, ",")
		var pictureList []string
		for _, picture := range pictures {
			pictureList = append(pictureList, fmt.Sprintf("%s%s", conf.Domain, picture))
		}
		trendsList[i].Trends.Pictures = pictureList
		trendsList[i].Trends.AnimationData = map[string]interface{}{}
		trendsList[i].Trends.VideoUrl = fmt.Sprintf("%s%s", conf.Domain, trends.Trends.VideoUrl)
		trendsList[i].Trends.CoverPicture = fmt.Sprintf("%s%s", conf.Domain, trends.Trends.CoverPicture)
	}

	data := map[string]interface{}{
		"list": trendsList,
	}

	return utils.CommonRes(20000, "成功获取动态列表", data)
}

// 用户删除自己的说说
func (c *Trends) PostDel() interface{} {
	channel := c.Ctx.PostValue("channel")
	id := strings.TrimSpace(c.Ctx.PostValueDefault("trendsId", "0"))

	var userId int64
	if strings.EqualFold(channel, "wechat") {
		token := c.Ctx.GetHeader("token")
		claims, err := utils.ParseToken(token)
		if err != nil {
			return utils.CommonRes(1000, fmt.Sprintf("解析token出错：%s", err.Error()), "")
		}
		userId = utils.Atoi64(claims.Id)
	} else {
		session := sessions.Get(c.Ctx)
		userId, _ = session.GetInt64(fmt.Sprintf("%sUserId", channel))
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	trends := new(models.Trends)
	ok, err := db.Where("`id` = ? and `user_id` = ?", id, userId).Get(trends)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("说说删除失败:%s", err.Error()), "")
	}
	if !ok {
		return utils.CommonRes(1000, "要删除的说说不存在", "")
	}

	commentList := make([]models.Comment, 0)
	db.Where("`trends_id` = ?", trends.Id).Find(&commentList)
	for _, comment := range commentList {
		db.ID(comment.Id).Unscoped().Delete(comment)
	}

	thumbsUpList := make([]models.ThumbsUp, 0)
	db.Where("`trends_id` = ?", trends.Id).Find(&thumbsUpList)
	for _, thumbsUp := range thumbsUpList {
		db.ID(thumbsUp.Id).Unscoped().Delete(thumbsUp)
	}

	if len(trends.CoverPicture) > 0 {
		coverPicUrl := fmt.Sprintf("%s%s", conf.UploadPrefix.Front, trends.CoverPicture)
		_, err = os.Stat(coverPicUrl)
		if err == nil {
			os.Remove(coverPicUrl)
		}
	}

	if len(trends.VideoUrl) > 0 {
		videoUrl := fmt.Sprintf("%s%s", conf.UploadPrefix.Front, trends.VideoUrl)
		_, err = os.Stat(videoUrl)
		if err == nil {
			os.Remove(videoUrl)
		}
	}

	picList := strings.Split(trends.PictureList, ",")
	if len(picList) > 0 {
		for _, pic := range picList {
			picUrl := fmt.Sprintf("%s%s", conf.UploadPrefix.Front, pic)
			_, err = os.Stat(picUrl)
			if err == nil {
				os.Remove(picUrl)
			}
		}
	}

	db.ID(id).Unscoped().Delete(trends)

	return utils.CommonRes(20000, "成功删除", "")
}
